<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>1111</title>
</head>
<body>
<!--反斜杠 在不同操作系统下不一样 空格永远是空格 -->

<input type="text" id="uid" placeholder="请输入信息"/><br>
<button onclick="onConnectionClick();">连接服务器</button><br>
<input type="text" id="msg" placeholder="请输入信息"/><br>
<button onclick="sendMessage();">发送消息</button><br>
<div id="messages"></div>

<script>
    function sendMessage() {
        let message = document.getElementById("msg").value;
        socket.send(message);
    }

    let socket;

    function onConnectionClick() {
        if (typeof (WebSocket) == "undefined") {
            alert("请使用新版本的浏览器")
        } else {
            //浏览器支持websocket
            if (socket != null) {
                socket.close();
                socket = null;
            }

            let uid = document.getElementById("uid").value;
            //websocket 协议的url

            let url = "ws://localhost:9002/webSocket/" + uid;
            //web实例话
            socket = new WebSocket(url);

            //连接

            socket.onopen = function () {
                alert("连接成功");
            };
            //会话
            socket.onmessage=function(msg){
                document.getElementById("messages").innerHTML+=(msg.data+"<br>");
            };
            //关闭
            socket.onclose = function () {
                alert("连接已经关闭")
            };
            //错误
            socket.onerror = function () {
                alert("连接发生异常")
            };
        }
    }
</script>
</body>
</html>